package com.edu.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class MyStringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        SimpleDateFormat dateFormat = null;
        Date date = null;
        try {
            if (Pattern.matches("^\\d{4}/\\d{1,2}/\\d{1,2}$",source)) {
                dateFormat = new SimpleDateFormat("yyyy/MM/dd");
                date = dateFormat.parse(source);
            } else if (Pattern.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$",source)) {
                dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                date = dateFormat.parse(source);
            } else {
                throw new ClassCastException("输入的字符"+source+"有误，请检查");
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return date;
    }
}
